package pl.mdziedzic.unittests.selenium;

import static org.fest.assertions.Assertions.assertThat;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

public abstract class Page {

	public static final String BASE_URL = "https://www.nazwa.pl/";

	protected final WebDriver driver;

	protected final WebDriverWait wait;

	private String relativeUrl;

	private String title;

	public Page(WebDriver driver) {
		this.driver = driver;
		wait = new WebDriverWait(driver, 10);
	}

	protected Page(WebDriver driver, String relativeUrl) {
		this(driver);
		this.relativeUrl = relativeUrl;
	}
	
	protected Page(WebDriver driver, String relativeUrl, String title) {
		this(driver, relativeUrl);
		this.title = title;
	}
	
	public void open() {
		if (relativeUrl != null) {
			driver.get(BASE_URL + relativeUrl);
			verifyIsOnThePage();
    }
	}
	
	public void verifyIsOnThePage() {
		if (title != null) {
	    verifyTitle(title);
    }
	}

	protected void verifyTitle(String expected) {
		assertThat(driver.getTitle()).isEqualTo(expected);
	}

	protected void verifyTextPresent(String expected) {
		assertThat(driver.getPageSource()).contains(expected);
	}

	protected void waitForElement(By by) {
		wait.until(new ElementPresentCondition(by));
	}

	protected void forceWait() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	protected void insertText(String elementId, String name) {
		WebElement element = findById(elementId);
		element.sendKeys(name);
	}

	protected void insertTextAndSubmit(String elementId, String name) {
		WebElement element = findById(elementId);
		element.sendKeys(name);
		element.submit();
	}

	protected void click(String elementId) {
		WebElement element = findById(elementId);
		element.click();
	}

	protected void clickAndSubmit(String elementId) {
		WebElement element = findById(elementId);
		
		System.out.println("elementId -> " + elementId);
		System.out.println("result -> " + element.getTagName());
		
		element.click();
		element.submit();
	}

	protected WebElement findById(String elementId) {
		return driver.findElement(By.id(elementId));
	}

}
